package com.laizhenghua.share.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laizhenghua.share.common.core.context.SecurityContextHolder;
import com.laizhenghua.share.common.core.enums.UserStatus;
import com.laizhenghua.share.user.api.constant.DepositStatus;
import com.laizhenghua.share.user.api.domain.entity.UserInfo;
import com.laizhenghua.share.user.mapper.UserInfoMapper;
import com.laizhenghua.share.user.service.IUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户Service业务层处理
 *
 * @author laizhenghua
 * @date 2025-10-10
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private final WxMaService wxMaService;

    @Autowired
    public UserInfoServiceImpl(WxMaService wxMaService) {
        this.wxMaService = wxMaService;
    }

    @Override
    public List<UserInfo> selectUserInfoList(UserInfo userInfo) {
        return baseMapper.selectUserInfoList(userInfo);
    }

    @Override
    public UserInfo wxLogin(String code) {
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        } catch (Exception ex) {
            log.error("----> get WxMaJscode2Session error: {}", ex.getMessage(), ex);
            return null;
        }
        String openid = sessionInfo.getOpenid();
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getWxOpenId, openid);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(userInfo)) {
            // 注册
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname(String.valueOf(System.currentTimeMillis())); // 默认使用时间戳作为用户名
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setStatus(UserStatus.OK.getCode());
            baseMapper.insert(userInfo);
        }
        return userInfo;
    }

    @Override
    public Boolean isFreeDeposit() {
        Long userId = SecurityContextHolder.getUserId();
        UserInfo userInfo = baseMapper.selectById(userId);
        // TODO 模拟微信支付信用判断
        userInfo.setDepositStatus(DepositStatus.DEPOSIT_DISMISS.getStatus());
        baseMapper.updateById(userInfo);
        return true;
    }
}
